<template>
	<view>
		<uni-forms :rules="rules" :value="formData" ref="form" validate-trigger="bind" err-show-type="undertext">
			<uniGroup title="事件信息" top="0" :icon="icon" @submit="submit" @delete="deleteEvent">
				<uni-forms-item name="eventTypeId" label="类型">
					<div class="uni-event-type" @click="showPicker"
						:style="{ color: eventTypeLabel ? 'black' : '#666' }">{{
			eventTypeLabel || "请选择" }}</div>
				</uni-forms-item>
				<uni-forms-item name="eventTitle" required label="内容">
					<uni-easyinput type="text" :inputBorder="true" v-model="formData.eventTitle"
						placeholder="请输入事件标题"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item required name="eventStart" label="开始">
					<uni-data-select v-model="formData.eventStart" :localdata="eventTime"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item required name="eventEnd" label="结束">
					<uni-data-select v-model="formData.eventEnd" :localdata="eventTime"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="targetId" label="目标">
					<uni-data-select v-model="formData.targetId" :localdata="targetList"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="eventColor" label="颜色">
					<div :style="{ background: formData.eventColor, height: '100%', borderRadius: '10rpx', border: '2rpx #e5e5e5 solid' }"
						@click="openColor"></div>
				</uni-forms-item>
				<uni-forms-item name="eventNotes" label="备注">
					<uni-easyinput type="textarea" v-model="formData.eventNotes" placeholder="请输入事件备注"></uni-easyinput>
				</uni-forms-item>
			</uniGroup>
		</uni-forms>
		<view>
			<t-color-picker ref="colorPicker" :color="color" @confirm="confirmColor"></t-color-picker>
			<ba-tree-picker ref="treePicker" :multiple='false' @select-change="selectChange" title="选择事件类型"
				:localdata="eventTypeTree" valueKey="id" textKey="label" childrenKey="children" />
		</view>
	</view>
</template>

<script>
import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue";
import uniGroup from '@/components/uni-group/uni-group.vue'
export default {
	components: {
		baTreePicker,
		uniGroup
	},
	data() {
		return {
			icon: [{
				src: '../../static/interaction/edit-active.png',
				emit: 'submit'
			},
			{
				src: '../../static/interaction/delete-active.png',
				emit: 'delete'
			}],
			date: '',
			eventTypeTree: [],
			newTree: [],
			eventTypeLabel: '',
			targetList: [],
			formData: {
				eventId: 0,
				eventTitle: '',
				eventDate: '',
				eventStart: '',
				eventEnd: '',
				eventTypeId: 1,
				eventNotes: '',
				targetId: 1,
				eventColor: ''
			},
			color: { r: 255, g: 255, b: 255, a: 1 },
			rules: {
				eventTitle: {
					rules: [{
						required: true,
						errorMessage: '请输入事件标题'
					},
					{
						maxLength: 15,
						errorMessage: '目标内容在 {maxLength} 个字符以内'
					}
					]
				},
				eventStart: {
					rules: [{
						format: 'number'
					}]
				},
				eventEnd: {
					rules: [{
						format: 'number'
					}]
				},
				eventTypeId: {
					rules: [{
						format: 'number'
					}]
				},
				targetId: {
					rules: [{
						format: 'number'
					}]
				},
				eventNotes: {
					rules: [{
						format: 'string'
					}]
				},
				eventColor: {
					rules: [{
						format: 'string'
					}]
				}
			}
		}
	},
	computed: {
		eventTime() {
			let time = []
			for (let i = 0; i < 24; i++) {
				let hour = i < 10 ? '0' + i : i
				time.push({
					value: 2 * i,
					text: hour + ':00'
				})
				time.push({
					value: 2 * i + 1,
					text: hour + ':30'
				})
			}
			time.push({
				value: 48,
				text: 24 + ':00'
			})
			return time
		}
	},
	async onShow(){
		let event = uni.getStorageSync('event')
		await this.getEventTypeList()
		await this.getTargetList()
		await this.setFormData(event)
		let date = event.eventDate
		this.setDefaultDate(date)
	},
	methods: {
		setFormData(event) {
			if (event) {
				event.eventStart = this.eventTime.findIndex(item => item.text == event.eventStart.slice(11, 16))
				if(event.eventEnd.slice(11, 16) == '23:59') {
					event.eventEnd = this.eventTime.findIndex(item => item.text == '24:00')
				}else{
					event.eventEnd = this.eventTime.findIndex(item => item.text == event.eventEnd.slice(11, 16))
				}
				for (let key in this.formData) {
					this.formData[key] = event[key]
				}
				this.newTree.forEach(item => {
					if (item.id == event.eventTypeId) {
						this.eventTypeLabel = item.label
						item.checked=true
					}
				})
			}
			this.eventTypeTree = this.newTree
		},
		async deleteEvent(){
			let result = await this.$API.event.deleteEvent({eventId: this.formData.eventId})
				if (result.code == 200) {
					uni.showToast({
						title: result.data,
						icon: 'none',
						duration: 1000
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				} else {
					uni.showToast({
						title: result.msg,
						icon: 'none',
						duration: 1000
					})
				}
		},
		getDate(type) {
			const date = new Date();
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();

			if (type === 'start') {
				year = year - 60;
			} else if (type === 'end') {
				year = year + 2;
			}
			month = month > 9 ? month : '0' + month;
			day = day > 9 ? day : '0' + day;
			return `${year}-${month}-${day}`;
		},
		setDefaultDate(date) {
			this.date = date ? date : this.getDate({
				format: true
			})
		},
		async getTargetList() {
			let result = await this.$API.target.getTargetList({
				page: {
					current: 1,
					size: 1000
				}
			})
			if (result.code == 200) {
				result.data.records.forEach(item => {
					this.targetList.push({
						text: item.targetDetail,
						value: item.targetId
					})
				})
			}
		},
		async getEventTypeList() {
			let result = await this.$API.eventType.getEventTypeList()
			this.newTree = []
			if (result.code === 200) {
				result.data.forEach(item => {
					let newItem = {
						label: item.eventTypeLabel,
						id: item.eventTypeId,
						pid: 0,
						color: item.eventTypeColor,
						children: []
					}
					item.eventTypeChildList.forEach(child => {
						newItem.children.push({
							id: child.eventTypeChildId,
							label: child.eventTypeChildLabel,
							color: item.eventTypeColor,
							pid: item.eventTypeId,
							targetId: child.targetId
						})
					})
					this.newTree.push(newItem)
				})
			}
			
		},
		// 显示选择器
		showPicker() {
			this.$refs.treePicker._show();
		},
		//监听选择（）
		selectChange(row, status) {
			if (status == 0) {
				this.eventTypeLabel = ''
				this.formData.eventTypeId = ''
				this.formData.eventTitle = ''
				this.formData.targetId = ''
				this.formData.eventColor = ''
				return
			}
			this.eventTypeLabel = row.name
			this.formData.eventTypeId = row.pid == 0 ? row.id : row.pid
			this.formData.eventTitle = row.name
			this.formData.targetId = row.targetId
			this.formData.eventColor = row.color
		},
		openColor(item) {
			// 打开颜色选择器
			this.$refs.colorPicker.open();
		},
		confirmColor(e) {
			this.formData.eventColor = e.hex
		},
		submit() {
			this.$refs['form']
				.validate()
				.then(async res => {
					if(this.formData.eventStart >= this.formData.eventEnd) {
						uni.showToast({
							title: '结束时间应大于开始时间',
							icon: 'none',
							duration: 1000
						})
						return
					}
					let text = this.eventTime[this.formData.eventEnd].text
					let eventEnd = ''
					if (text == '24:00') {
						eventEnd= this.date + 'T' + '23:59'
					}else{
						eventEnd = this.date + 'T' + text
					}
					let result = await this.$API.event.saveOrUpdateEvent({
						...this.formData,
						eventDate: this.date,
						eventStart: this.date +'T'+ this.eventTime[this.formData.eventStart].text,
						eventEnd: eventEnd
					})
					if (result.code == 200) {
						uni.showToast({
							title: result.data,
							icon: 'none',
							duration: 1000
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none',
							duration: 1000
						})
					}
				})
				.catch(errors => {
					if (errors[0]) {
						uni.showToast({
							title: errors[0].errorMessage,
							icon: "none"
						})
					}
				})
		},
	}
}
</script>

<style>
.uni-input-border {
	padding: 0 20rpx;
	height: 70rpx;
	width: 100%;
	font-size: 28rpx;
	color: #666;
	border: 2rpx #e5e5e5 solid;
	border-radius: 10rpx;
	box-sizing: border-box;
}

.uni-event-type {
	display: flex;
	align-items: center;
	padding-left: 20rpx;
	height: 74rpx;
	width: 100%;
	font-size: 24rpx;
	border: 2rpx #e5e5e5 solid;
	border-radius: 10rpx;
	box-sizing: border-box;
}
</style>